<template>
  <div class="app-container">
    <div class="filter-container">
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate" >
            添加
        </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="编号"  align="center" >
        <template slot-scope="{row}">
          <span>  {{ row.id }}</span>
        </template>
      </el-table-column>
     
      <el-table-column label="文件名称" align="center"> 
        <template slot-scope="{row}">
          <span class="link-type" >{{ row.filename }}</span>
        </template>
      </el-table-column>
     
      <el-table-column label="文件地址" min-width="110px" align="center">
        <template slot-scope="{row}">
          <span ><a :href="row.filepath"  target="_blank"  >{{ row.filepath }}</a></span>
        </template>
      </el-table-column>
    
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
            
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
                编辑
            </el-button>
          <el-popconfirm
              confirm-button-text="是"
              cancel-button-text="取消"
              icon-color="red"
              title="你是否确定删除此数据?"
                @onConfirm="handleDelete(row,$index)"
            >
              <template #reference>
                <el-button size="mini" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
      
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" >
       
        
        <el-form-item label="文件名称" prop="filename" >
          <el-input v-model="temp.filename"/>
        </el-form-item>
        
         <el-form-item label="文件" prop="filepath">
            <template>
                <el-upload
                        class="upload-demo"
                        ref="upload"
                        :action="domain"
                        :data="QiniuData"
                        :show-file-list="true"
                        :on-success="uploadSuccess"
                        :before-remove="beforeRemove"
                        :limit="1"
                        :before-upload="beforeAvatarUpload">
                    <el-button type="primary">上传文件</el-button>
                </el-upload>
            </template>
         
         </el-form-item>
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { GQL } from '@/api/article'
import { getToken } from '@/api/qiniu'

export default {
  name: 'ComplexTable',

  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      fid:'',
        temp:{
            filepath:'',
            filename:'',
        },
      rules: {
        filename: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }]
      },
      showReviewer: false,
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
            update: '编辑文件',
            create: '新增文件'
        },
        QiniuData: {
        key: "yssl", //图片名字处理
        token: "" ,//七牛云token
        data:{}
      },
      domain: "http://upload-z2.qiniup.com", // 七牛云的上传地址（华东区）
       qiniuaddr: "http://r92t5xgkc.hn-bkt.clouddn.com", // 七牛云的
    }
  },
  created() {
    let id=this.$route.query.id;
   
    this.fid = id
     this.getList()
      this.Qiniutoken()
  },
  methods: {
    Qiniutoken(){
        getToken().then(response => {
          // console.log('77777777777',response)
           this.QiniuData.token= response.data
        //   resolve(true)
        })
    },
  
  
    beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
    },
    beforeAvatarUpload(file) { 
        const isLt2M = file.size / 1024 / 1024 < 4;
        if (!isLt2M) {
          this.$message.error("上传文件大小不能超过 4MB!");
          return false;
        }
        // file.name = 
        var time = new Date().getTime();
        const filename = time + file.name;
        this.QiniuData.data = file;
        this.QiniuData.key = filename;
    },

    uploadSuccess(response, file, fileList) { 

      this.temp.filepath = `${this.qiniuaddr}/${response.key}`;
    },
    getList() {
      this.listLoading = true
        const query = {
               "operationName": "allSlProjectFolderFiles",
                "query": "query allSlProjectFolderFiles($filter: SlProjectFolderFileFilter) { allSlProjectFolderFiles(filter:$filter) { nodes { createtime fid filename filepath id } } }",
                "variables":{ "filter": { "fid": { "equalTo": this.fid } }}
        }
        GQL(query).then(response => {
            this.list = response.data.allSlProjectFolderFiles.nodes
            setTimeout(() => {
            this.listLoading = false
            }, 1.5 * 1000)
        })
      
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        filename:'',
        filepath:'',
      }
    },
     handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
       handleUpdate(row) {
    //   this.resetTemp()
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(){
        this.temp.fid = this.fid
        const query = {
          "operationName": "createSlProjectFolderFile",
          "query": "mutation createSlProjectFolderFile($input: CreateSlProjectFolderFileInput!) { createSlProjectFolderFile(input: $input) { slProjectFolderFile { id } } }",
          "variables": {"input": {"slProjectFolderFile": this.temp}}
        }
        console.log('2=-=',query)
       
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          GQL(query).then((res) => {
               console.log('2=-=',res)
            if(res.errors){
                this.$notify({
                  title: '添加失败',
                  message: '新增文件失败',
                  type: 'error',
                  duration: 2000
                })
            }else{
              this.temp.id = res.data.createSlProjectFolderFile.slProjectFolderFile.id
               this.list.unshift(this.temp)
                this.dialogFormVisible = false
                this.$notify({
                  title: '添加成功',
                  message: '新增文件成功',
                  type: 'success',
                  duration: 2000
                })
                
            }
          })
        }
      })
    },
     updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          console.log('1---',this.temp)
           const query = {
            "operationName": "updateSlProjectFolderFileById",
            "query": "mutation updateSlProjectFolderFileById($input: UpdateSlProjectFolderFileByIdInput!) { updateSlProjectFolderFileById(input: $input) { slProjectFolderFile { id } } }",
            "variables": { "input": { "id":this.temp.id ,"slProjectFolderFilePatch": this.temp } }
            }
          GQL(query).then((res) => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
               if(res.errors){
                  this.$notify({
                    title: '修改文件失败',
                    message: '修改文件失败',
                    type: 'error',
                    duration: 2000
                  })
              }else{
                  this.list.splice(index, 1, this.temp)
                  this.dialogFormVisible = false
                  this.$notify({
                    title: '修改文件成功',
                    message: '修改文件成功',
                    type: 'success',
                    duration: 2000
                  })
              }
          })
        }
      })
    },
    handleDelete(row, index) {
       
          let query = {
            "operationName": "deleteSlProjectFolderFileById",
            "query": "mutation deleteSlProjectFolderFileById($input: DeleteSlProjectFolderFileByIdInput!) { deleteSlProjectFolderFileById(input: $input) { slProjectFolderFile { id } } }",
            "variables": {input: {id: row.id}}
          }
          GQL(query).then((res) => {
               if(res.errors){
                  this.$notify({
                    title: '删除失败',
                    message: '删除文件失败',
                    type: 'error',
                    duration: 2000
                  })
              }else{
                  this.$notify({
                    title: '删除成功',
                    message: '删除文件成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.list.splice(index, 1)
              }
      
          })
        
    }
  }
}
</script>
<style scoped>
.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 350px;
    height: 180px;
    display: block;
  }
</style>
